package com.kaishengit.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.dao.UserDao;
import com.kaishengit.entity.User;

public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 873340309782350462L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String method = request.getParameter("_method");
		
		if(null == method || "".equals(method)) {
			list(request,response);
		} else if("save".equals(method)) {
			save(request,response);
		} else if("update".equals(method)) {
			update(request,response);
		} else if("login".equals(method)) {
			login(request,response);
		} else if("_add".equals(method)) {
			toAdd(request,response);
		} else {
			response.sendError(404);
		}
		
	}

	private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		//?
		//select type
		//setAttr(type)
		request.getRequestDispatcher("main.jsp").forward(request, response);
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserDao userDao = new UserDao();
		User user = userDao.login(username, password);
		if(user == null) {
			response.sendRedirect("index.jsp?state=001");
		} else {
			HttpSession session = request.getSession();
			session.setAttribute("CURRUSER", user);
			response.sendRedirect("user.jspx");
		}
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserDao dao = new UserDao();
		int rows = dao.save(username, password);
		if(rows > 0) {
			response.sendRedirect("user.jspx");
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserDao dao = new UserDao();
		List<User> list = dao.findAll();
		request.setAttribute("list", list);
		request.getRequestDispatcher("list.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}

}
